//
//  MNDCreditorDetailViewController.m
//  minidai
//
//  Created by 谭谭伟 on 2017/5/31.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDCreditorDetailViewController.h"
#import "MNCreditorDetailTopCell.h"
#import "MNDFinaceDetailModel.h"
#import "MNDFinanceAlertViewController.h"
#import "MNDLoginUserModel.h"
#import "MNDFinanceViewController.h"
#import "SYRefreshControl.h"
#import "MNDDepositAlertViewController.h"
#import "MNDCreditorInvestViewController.h"
#import "MNDWebViewController.h"
#import "MNDDepositWebViewController.h"
#import "MNDOpenDeposAlertViewController.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDOpenDepositoryTenderViewController.h"
#import "MNDOpenDepositoryTransferViewController.h"
#import "MNDUserModel.h"
#import "MNDRiskAssessWebViewController.h"

@interface MNDCreditorDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *investButton;
@property (nonatomic,strong) MNDFinaceDetailModel *detaiModel;

@property (nonatomic, strong) MNDUserModel *userModel;

@end

@implementation MNDCreditorDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showInvestButton) name:@"showInvestButton" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDetailModel:) name:@"senderCreditorCode" object:nil];
    [self setupUI];
    
    if (@available(iOS 11, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        
    }
    
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if ([MNDLoginUserModel isUserLogin]) {

        [self loadUserInfo];
    }
}

- (void)showInvestButton {
    self.investButton.hidden = NO;
}

- (void)getDetailModel:(NSNotification *)notification{
    self.borrowCode = [notification.object objectForKey:@"borrowCode"];
    self.creditorCode = [notification.object objectForKey:@"creditorCode"];
    [self loadData];
}

- (void)configContents {
    NSDictionary *dict = @{@"detailModel":self.detaiModel};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"senderDetailModel" object:dict];
    if ([self.detaiModel.creditor_status isEqualToString:@"1"]) {
        self.investButton.enabled = YES;
        [self.investButton setBackgroundImage:[UIImage imageNamed:@"creditor_detail_normal"] forState:UIControlStateNormal];
    }else {
        self.investButton.enabled = NO;
        [self.investButton setBackgroundImage:nil forState:UIControlStateNormal];
        [self.investButton setBackgroundColor:[UIColor colorWithRed:181/255.0 green:181/255.0 blue:181/255.0 alpha:1.0]];
        if (self.detaiModel.creditor_status.integerValue == 2) {
            
            [self.investButton setTitle:@"已撤销" forState:UIControlStateDisabled];
        } else if (self.detaiModel.creditor_status.integerValue == 4) {
            [self.investButton setTitle:@"已完成" forState:UIControlStateDisabled];
        }
    }
}

#pragma mark -跳转到投资页
- (IBAction)goInvestAction:(UIButton *)sender {
    //未登录，先登录
    if (![MNDLoginUserModel isUserLogin]) {
        
        [self goToLoginVC];
        
        return;
    }
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:[NSBundle mainBundle]];
    MNDCreditorInvestViewController *creditorInvestVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDCreditorInvestViewController"];
    creditorInvestVC.creditorCode = self.detaiModel.creditor_code;
    creditorInvestVC.borrowCode = self.detaiModel.borrow_code;
    [self.navigationController pushViewController:creditorInvestVC animated:YES];
}

- (void)loadUserInfo {
    
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_BASE_INFO parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            weakself.userModel = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
            
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)showRiskAlertView {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有完成[出借用户风险等级测评]，根据金融监管政策要求，用户需要先完成评估才能出借。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"去测评" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
        
        MNDRiskAssessWebViewController *riskVC = [[MNDRiskAssessWebViewController alloc]init];
        riskVC.webViewUrl = self.userModel.evaluationUrl;
        riskVC.indexOfViewController = index;
        riskVC.title = @"风险测评";
        [self.navigationController pushViewController:riskVC animated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

/**
 设置交易密码
 */
- (void)loadPaymentPassword {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SET_PASSWORD parameters:[MNDSign signedParamWithDict:@{@"channel": @"app"}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"设置交易密码";
            NSInteger index = [weakself.navigationController.viewControllers indexOfObject:weakself];
            webVC.fromNaviIndex = index;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

#pragma mark -没有登录，跳转到登录页面

- (void)goToLoginVC {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

#pragma mark -加载数据
- (void)loadData {
    __weak typeof(self) weakSelf = self;
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"borrow_code":self.borrowCode,@"creditor_code":self.creditorCode}];
    
    [APIManager sendRequestWithPath:API_FINANCE_DETAIL parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {

            weakSelf.detaiModel = [MNDFinaceDetailModel mj_objectWithKeyValues:responseModel.data];
            [weakSelf configContents];
            [weakSelf.tableView reloadData];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
        [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:YES];
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:YES];
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)setupUI {
    
    WeakSelf(self);
    [SYRefreshControl configGifMJRefresh:self.tableView refreshType:MJRefreshSupportRefresh beginRefresh:NO timeLabelHidden:YES stateLabelHidden:YES refreshBlock:^{
        [weakself loadData];
    } loadMoreBlock:nil];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - TableViewDataSource, UITableViewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MNCreditorDetailTopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNCreditorDetailTopCell"];
    cell.discountAprLabel.text = [NSString stringWithFormat:@" %@%%折扣转让 ",self.discountStr];
    [cell.transferConditionButton addTarget:self action:@selector(showTransferConditionAlert) forControlEvents:UIControlEventTouchUpInside];
    if (self.detaiModel != nil ) {
        cell.detaiModel = self.detaiModel;
    }
    return cell;
}

- (void)showTransferConditionAlert {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDFinanceAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDFinanceAlertViewController"];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
    [alertVC.alertBtn bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat presentHeight = scrollView.contentOffset.y - (scrollView.contentSize.height - screenHeight);
    NSLog(@"-----%f-----",scrollView.contentOffset.y);
    NSLog(@"velocity = %f",velocity.y);
    //大于60，向上滚动
    if (velocity.y >0) {
        
        if (presentHeight >= 140) {
            self.investButton.hidden = YES;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [scrollView setContentOffset:CGPointMake(0, 0)];
            });
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll_up_or_down" object:@1];
            
        }
    }
    
}

//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
//    //    if (self.delegate && [self.delegate respondsToSelector:@selector(topViewViewDidEndDragging:)]) {
//    //
//    //        [self.delegate topViewViewDidEndDragging:self.tableView];
//    //    }
//    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
//    CGFloat presentHeight = scrollView.contentOffset.y - (scrollView.contentSize.height - screenHeight);
//    
//    //大于60，向上滚动
//    if (presentHeight >= 60) {
//        self.investButton.hidden = YES;
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll_up_or_down" object:@1];
//    }
//}

//风险揭示书
- (IBAction)checkRiskExplainAction:(UIButton *)sender {
    MNDWebViewController *webVC = [[MNDWebViewController alloc] init];
    webVC.webViewUrl = kRiskExplain;
    webVC.title = @"风险揭示书";
    //    webVC.naviBarHidden = NO;
    
    [self.navigationController pushViewController:webVC animated:YES];
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
